﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Configuration;
using System.Web.Configuration;

namespace SPWP.OpinionPoll
{
    public class QueryList
    {
        private string listLocation = WebConfigurationManager.AppSettings["listpoll"].ToString();

        public string SPPollSite { get; set; }
        public string SPPollList { get; set; }

        string spsite;

        public QueryList(string splist)
        {
            spsite = SPPollSite;
            SPPollList = splist;
        }

        /// <summary>
        /// Add new poll
        /// </summary>
        /// <param name="itemAdd">New poll details</param>
        /// <returns>Status message</returns>
        public string AddPoll(PollMaster itemAdd)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        if (String.Compare(itemAdd.IsActive, "Yes", true) == 0)
                        {
                            if (!UnpublishPoll())
                                throw new Exception("Existing polls cannot be unpublished");
                        }

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItem objItem = objList.Items.Add();
                        objItem["Title"] = itemAdd.PollTitle;
                        objItem["ExpiresOn"] = itemAdd.ExpireOn;
                        objItem["SortOrder"] = itemAdd.SortOrder;
                        objItem["Active"] = itemAdd.IsActive;
                        objItem["AnonsCanVote"] = itemAdd.AnonymousVote;
                        objItem["MultipleChoice"] = itemAdd.MultiChoice;
                        //objItem["Category"] = itemAdd.Category;

                        objItem.Update();

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return "Poll added successfully";

                    }
                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }
        }

        /// <summary>
        /// Edit existing poll details
        /// </summary>
        /// <param name="itemEdit">Latest poll details</param>
        /// <returns>Status message</returns>
        public string UpdatePoll(PollMaster itemEdit)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        if (String.Compare(itemEdit.IsActive, "Yes", true) == 0)
                        {
                            if (!UnpublishPoll())
                                throw new Exception("Existing polls cannot be unpublished");
                        }

                        SPQuery objQuery = new SPQuery();
                        string ID = itemEdit.PollID.ToString();  // hidden field
                        objQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ID + "</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];

                        SPListItem objItem = objList.GetItemById(int.Parse(ID));

                        objItem["Title"] = itemEdit.PollTitle;
                        objItem["ExpiresOn"] = itemEdit.ExpireOn;
                        objItem["SortOrder"] = itemEdit.SortOrder;
                        objItem["Active"] = itemEdit.IsActive;
                        objItem["AnonsCanVote"] = itemEdit.AnonymousVote;
                        objItem["MultipleChoice"] = itemEdit.MultiChoice;
                        //objItem["Category"] = itemEdit.Category;
                        objItem.Update();

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return "Poll updated successfully";

                    }
                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }

        }

        /// <summary>
        /// Publish / unpublish poll result
        /// </summary>
        /// <param name="idEdit">Poll ID</param>
        /// <returns>Status message</returns>
        public string PublishPoll(int pollID)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPQuery objQuery = new SPQuery();
                        string ID = pollID.ToString();  // hidden field
                        //objQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ID + "</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItem objItem = objList.GetItemById(int.Parse(ID));

                        bool isPublish = Convert.ToBoolean(objItem["PublishResult"].ToString());
                        objItem["PublishResult"] = !isPublish;

                        objItem.Update();

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        string message = String.Empty;

                        if (!isPublish)
                            message = "Poll result published successfully";
                        else
                            message = "Poll result unpublished successfully";

                        return message;

                    }
                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }

        }

        /// <summary>
        /// Unpublish all poll
        /// </summary>
        /// <param name="itemEdit">Latest poll details</param>
        /// <returns>Status message</returns>
        public bool UnpublishPoll()
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPQuery objQuery = new SPQuery();
                        objQuery.Query = "<Where><Eq><FieldRef Name='Active' /><Value Type='Choice'>Yes</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];

                        SPListItemCollection objItem = objList.GetItems(objQuery);

                        foreach (SPListItem item in objItem)
                        {
                            if (String.Compare(item["Active"].ToString(), "Yes", true) == 0)
                            {                                 
                                item["Active"] = "No";
                                item.Update();
                            }
                        }

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return true;

                    }
                }
            }
            catch (Exception ex)
            {                
                return false;
            }

        }

        /// <summary>
        /// Delete poll
        /// </summary>
        /// <param name="delID">Poll ID to be deleted</param>
        /// <returns>Status message</returns>
        public string DeletePoll(int delID)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPQuery objQuery = new SPQuery();
                        string ID = delID.ToString();  // hidden field
                        objQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ID + "</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItem objItem = objList.GetItemById(int.Parse(ID));
                        objItem.Delete();

                        // get answer for this poll too
                        QueryAnswer objQueryAnswer = new QueryAnswer("Poll Answers");
                        List<PollAnswer> answerList = new List<PollAnswer>();

                        answerList = objQueryAnswer.ViewPollAnswerByID(Convert.ToInt32(ID));

                        if (answerList != null)
                        {
                            foreach (PollAnswer item in answerList)
                            {
                                if (item.PollID.Equals(Convert.ToInt32(ID)))
                                {
                                    // delete answer for this poll too
                                    objQueryAnswer.DeleteAnswer(item.ID);
                                }
                            }
                        }

                        // delete voting list too
                        string listTitle = "Poll Votes-" + ID;
                        SPList checkFirst = objWeb.Lists.TryGetList(listTitle);

                        if (null != checkFirst) // list exist
                        {
                            SPListCollection lists = objWeb.Lists;
                            SPList list = lists[listTitle];
                            System.Guid listGuid = list.ID; 
                            lists.Delete(listGuid);
                        }

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return "Poll deleted successfully";
                    }

                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }

        }

        /// <summary>
        /// Query one poll details
        /// </summary>
        /// <param name="pollID">Poll ID to be viewed</param>
        /// <returns>One poll details</returns>
        public PollMaster ViewPollByID(int pollID)
        {
            PollMaster foundPoll = new PollMaster();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" />";
                        query.Query = @"<Query><Where><And><IsNotNull><FieldRef Name=""Title"" /></IsNotNull><Eq><FieldRef Name=""ID"" /><Value Type='Counter'>" + pollID.ToString() + "</Value></Eq></And></Where></Query>";
                
                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);
                
                        foreach (SPListItem item in filteredItems)
                        {
                            if (pollID.Equals(Convert.ToInt32(item["ID"])))
                            { 
                                foundPoll.PollID = Convert.ToInt32(item["ID"]);
                                foundPoll.PollTitle = item["Title"].ToString();
                                foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                                foundPoll.SortOrder = item["SortOrder"].ToString();
                                foundPoll.IsActive = item["Active"].ToString();
                                foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                                foundPoll.MultiChoice = item["MultipleChoice"].ToString();

                                //char[] separator = { '#' };
                                //string category = item["Category"].ToString().TrimStart(separator);

                                //foundPoll.Category = category;
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                 //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return foundPoll;

        }

        /// <summary>
        /// View all active polls
        /// </summary>
        /// <returns>List of active polls</returns>
        public List<PollMaster> ViewActivePoll()
        {
            List<PollMaster> foundPollList = new List<PollMaster>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" /><FieldRef Name=""PublishResult"" />";
                        query.Query = @"<Query><Where><And><IsNotNull><FieldRef Name=""Title"" /></IsNotNull><Eq><FieldRef Name=""Active"" /><Value Type='Choice'>Yes</Value></Eq></And></Where></Query>";
                        
                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);

                        foreach (SPListItem item in filteredItems)
                        {
                            PollMaster foundPoll = new PollMaster();

                            foundPoll.PollID = Convert.ToInt32(item["ID"]);
                            foundPoll.PollTitle = item["Title"].ToString();
                            foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                            foundPoll.SortOrder = item["SortOrder"].ToString();
                            foundPoll.IsActive = item["Active"].ToString();
                            foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                            foundPoll.MultiChoice = item["MultipleChoice"].ToString();
                            foundPoll.PublishResult = Convert.ToBoolean(item["PublishResult"].ToString());

                            //foundPoll.Category = item["Category"].ToString();

                            foundPollList.Add(foundPoll);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return foundPollList;

        }

        /// <summary>
        /// View all polls - active and inactive
        /// </summary>
        /// <returns>List of all polls</returns>
        public List<PollMaster> ViewAllPoll()
        {
            List<PollMaster> foundPollList = new List<PollMaster>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" /><FieldRef Name=""PublishResult"" />";
                        query.Query = @"<Query><OrderBy><FieldRef Name=""Created""></FieldRef></OrderBy><Where><IsNotNull><FieldRef Name=""Title"" /></IsNotNull></Where></Query>";

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);

                        foreach (SPListItem item in filteredItems)
                        {
                            PollMaster foundPoll = new PollMaster();

                            foundPoll.PollID = Convert.ToInt32(item["ID"]);
                            foundPoll.PollTitle = item["Title"].ToString();
                            foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                            foundPoll.SortOrder = item["SortOrder"].ToString();
                            foundPoll.IsActive = item["Active"].ToString();
                            foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                            foundPoll.MultiChoice = item["MultipleChoice"].ToString();
                            foundPoll.PublishResult = Convert.ToBoolean(item["PublishResult"].ToString());

                            char[] separator = {'#'};
                            string author = item["Author"].ToString().TrimStart(separator);
                            string editor = item["Editor"].ToString().TrimStart(separator);
                            //string category = item["Category"].ToString().TrimStart(separator);

                            //foundPoll.Category = category;

                            foundPoll.CreatedBy = author;
                            foundPoll.CreatedDate = DateTime.Parse(item["Created"].ToString());
                            foundPoll.ModifiedBy = editor;
                            foundPoll.ModifiedDate = DateTime.Parse(item["Modified"].ToString());

                            foundPollList.Add(foundPoll);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            DateComparer dc = new DateComparer();
            foundPollList.Sort(dc);

            return foundPollList;

        }

    }
}

